from flask import Blueprint, request, jsonify
from ..model.car_sales import CarSales
from ..extensions import db

# 创建蓝图
goods_bp = Blueprint('car_sales', __name__)

@goods_bp.route('/api/car_sales', methods=['GET'])
def get_car_sales():
    try:
        # 获取查询参数
        year = request.args.get('year', type=int)
        month = request.args.get('month', type=int)
        manufacturer = request.args.get('manufacturer')

        # 构建查询
        query = CarSales.query

        if year is not None:
            query = query.filter(CarSales.year == year)
        if month is not None:
            query = query.filter(CarSales.month == month)
        if manufacturer:
            query = query.filter(CarSales.manufacturer.like(f'%{manufacturer}%'))

            # 打印生成的 SQL 语句
            statement = query.statement
            print("Generated SQL:", statement.compile(compile_kwargs={"literal_binds": True}))

        # 执行查询
        results = query.all()

        # 序列化结果
        data = [{
            'id': car.id,
            'year': car.year,
            'month': car.month,
            'ranking': car.ranking,
            'model': car.model,
            'manufacturer': car.manufacturer,
            'sales_volume': car.sales_volume,
            'price_range': car.price_range
        } for car in results]

        return jsonify({
            "code": 0,
            "msg": "",
            "count": len(results),
            "data": [{
                'year': car.year,
                'month': car.month,
                'ranking': car.ranking,
                'model': car.model,
                'manufacturer': car.manufacturer,
                'sales_volume': car.sales_volume,
                'price_range': car.price_range
            } for car in results]
        })



    except Exception as e:
        print("发生错误:", str(e))
        return jsonify({"error": "查询失败"}), 500
